<template>
  <div class="login-box">
    <div>
      <header class="login-header">
        <div>
          <img src="/static/img/kxy.png" alt="LOGO" />
          <div>
            <p>矿校云</p>
            <span>kuangxiaoyun</span>
          </div>
        </div>
      </header>
      <main class="login-content">
        <div class="login-main">
          <h3 class="login-title">管理员登录</h3>
          <el-form
            :model="dataForm"
            :rules="dataRule"
            ref="dataForm"
            @keyup.enter.native="dataFormSubmit()"
            size="medium"
            status-icon
          >
            <el-form-item prop="userName">
              <el-input v-model="dataForm.userName" placeholder="帐号"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="dataForm.password"
                type="password"
                placeholder="密码"
                @change="isCookiePwd=false"
              />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-row :gutter="20">
                <el-col :span="14">
                  <el-input v-model="dataForm.captcha" placeholder="验证码" />
                </el-col>
                <el-col :span="10" class="login-captcha">
                  <img style="height: 34px" :src="captchaPath" @click="getCaptcha()" alt="图形验证码" />
                </el-col>
              </el-row>
            </el-form-item>
            <el-checkbox v-model="remember">记住密码</el-checkbox>
            <el-form-item>
              <el-button
                class="login-btn-submit"
                type="primary"
                @click="dataFormSubmit()"
                :loading="loginLoading"
              >登录</el-button>
            </el-form-item>
          </el-form>
        </div>
      </main>
      <footer class="login-footer">
        <div>请在不低于1440*900分辨率下使用，推荐使用谷歌浏览器和火狐浏览器；</div>
        <div>技术支持单位：矿校云科技；</div>
        <div>技术热线：18535644725；技术QQ：1458616285；</div>
      </footer>
    </div>
  </div>
</template>

<script>
import { getUUID } from '@/utils'
import { rsaEncrypt } from '@/utils/rsaUtils'

// const DayM = 86400

export default {
  data() {
    return {
      loginLoading: false,
      dataForm: {
        tenantId: '',
        userName: '',
        password: '',
        uuid: '',
        captcha: ''
      },
      isCookiePwd: false,
      remember: !!this.$cookie.get('remember') || false,
      tenantList: [],
      dataRule: {
        userName: [
          { required: true, message: '帐号不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '验证码不能为空', trigger: 'blur' }
        ]
      },
      captchaPath: ''
    }
  },
  created() {
    this.getCaptcha()
    if (this.$cookie.get('userName') && this.$cookie.get('userPwd')) {
      this.dataForm.userName = this.$cookie.get('userName')
      this.dataForm.password = this.$cookie.get('userPwd')
      this.isCookiePwd = true
    }
  },
  methods: {
    handlerChangeTenant(id) {
      this.$cookie.set('tenantId', id)
    },
    async getPubliccKey() {
      var res = await this.$http({
        url: this.$http.adornUrl('/auth/publickey'),
        method: 'post'
      })

      if (res.code === 200) {
        return res.data.publicKey
      }
      return false
    },
    // 提交表单
    dataFormSubmit() {
      const self = this
      this.$refs['dataForm'].validate(async valid => {
        if (valid) {
          this.loginLoading = true
          let publicKey = await this.getPubliccKey()

          let loginForm = {
            username: rsaEncrypt(this.dataForm.userName, publicKey),
            password: rsaEncrypt(this.dataForm.password, publicKey),
            formIn: 0,
            uuid: this.dataForm.uuid,
            captcha: this.dataForm.captcha
          }

          try {
            let loginRes = await this.$http({
              url: this.$http.adornUrl('/auth/admin/login'),
              method: 'post',
              data: loginForm
            })
            if (loginRes.code === 200) {
              this.setUserCookie({
                userId: loginRes.data.userId,
                userName: this.dataForm.userName,
                password: this.dataForm.password,
                token: loginRes.data.token,
                secret: loginRes.data.secret,
                tenantId: loginRes.data.tenantId,
                remember: self.remember,
                timeDiff: loginRes.data.t - new Date().getTime()
              })
              this.$router.replace(
                { name: 'home' },
                () => {
                  this.loginLoading = false
                },
                () => {
                  this.loginLoading = false
                }
              )
            } else {
              // 重新获取验证码，弹出登录错误提示
              this.getCaptcha()
              this.$message.warning(loginRes.msg)
              this.loginLoading = false
            }
          } catch (e) {
            this.loginLoading = false
            console.log(e)
          }
        }
      })
    },
    setUserCookie({
      userId,
      userName,
      password,
      token,
      secret,
      tenantId,
      remember,
      timeDiff
    }) {
      // 清空用户Cookie
      this.$cookie.delete('userName')
      this.$cookie.delete('userPwd')
      this.$cookie.delete('remember')

      // 设置用户Cookie信息
      this.$cookie.set('userId', userId)
      this.$cookie.set('token', token)
      this.$cookie.set('secret', secret)
      this.$cookie.set('tenantId', tenantId)
      this.$cookie.set('timeDiff', timeDiff)

      // 记住密码
      if (remember) {
        this.$cookie.set('userName', userName, 7)
        this.$cookie.set('userPwd', password, 7)
        this.$cookie.set('remember', true, 7)
      }
    },
    // 获取验证码
    getCaptcha() {
      this.dataForm.uuid = getUUID()
      this.captchaPath = this.$http.adornUrl(
        `/sys/captcha/captcha.jpg?uuid=${this.dataForm.uuid}`
      )
      console.log(this.captchaPath)
    }
  }
}
</script>

<style lang="scss">
.login-box {
  overflow: auto;

  & > div {
    display: flex;
    flex-wrap: wrap;
    flex-direction: column;
    min-height: 800px;
    height: 100%;
  }
}

.login-content {
  position: relative;
  flex: 1;
  background: url(~@/assets/img/kxy_login.jpeg) no-repeat left 30% top/cover;

  .login-main {
    position: absolute;
    top: 50%;
    right: 40px;
    transform: translateY(-50%);
    padding: 40px;
    width: 450px;
    height: 400px;
    background-color: #fff;

    .login-title {
      font-size: 16px;
    }

    .login-captcha {
      overflow: hidden;

      & > img {
        width: 100%;
        cursor: pointer;
      }
    }
  }
}

.login-header {
  width: 100%;
  padding: 0 60px;
  height: 70px;
  margin: 0 auto;

  & > div {
    width: 170px;
    padding: 15px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;

    img {
      width: 40px;
      height: 40px;
    }

    div {
      flex: 1;
      height: 40px;
    }

    p {
      margin: 0;
      line-height: 1.2;
      font-size: 20px;
      font-weight: bold;
      letter-spacing: 8px;
    }

    span {
      line-height: 0;
      font-size: 14px;
      font-weight: 300;
      letter-spacing: 0;
    }
  }
}

.login-btn-submit {
  width: 100%;
  margin-top: 38px;
}

.login-footer {
  text-align: center;
  font-size: 16px;
  height: 120px;
  line-height: 40px;
  color: #333;
}
</style>
